package com.xue.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.xue.web.service.LoginService;
import com.xue.web.utils.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginController {
    /**
     * 开始登录
     *
     * @param req  请求
     * @param resp 响应
     */
    public JSONObject startLogin(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println(this.getClass().getSimpleName()+"|校验用户输入");
        JSONObject jsonObject = new JSONObject();


        String userName = req.getParameter("userName");
        String userPassword =  req.getParameter("userPassword");

        if (StringUtils.isEmpty(userName)) {
            jsonObject.put("code", 400);
            jsonObject.put("msg", "账号还没输入");
            return jsonObject;
        }
        if (StringUtils.isEmpty(userPassword)) {
            jsonObject.put("code", 400);
            jsonObject.put("msg", "密码还没输入");
            return jsonObject;
        }

        System.out.println(this.getClass().getSimpleName() + "|校验成功");
        LoginService loginService = new LoginService();


        jsonObject = loginService.doLoging(userName, userPassword);
        if (jsonObject.get("code").equals((Integer)200)){
            //添加个cookie
            Cookie cookie= new Cookie(userName,userPassword);
            cookie.setPath("/");
            cookie.setMaxAge(60*60*24);
            resp.addCookie(cookie);
            //在session中存入用户
            req.getSession().setAttribute("user",userName);
        }
        return jsonObject;

    }
}
